﻿$(document).ready(function () {
    bindLoadingPopupForUpdatePanels();
    bindMegaMenu();
});

function bindLoadingPopupForUpdatePanels() {
    // Show loading popup for update panels
    var pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
    pageRequestManager.add_initializeRequest(function () {
        $('#global-loading-popup').openPopUp();
    });

    pageRequestManager.add_endRequest(function () {
        $.closePopUp();
    });
}

function bindMegaMenu() {
    $('#menu ul div, .loading').bgiframe();

    var megaMenu = $(".mega-menu");
    window.onpageshow = function () {
        //reset all items before do anything
        $('.mega-menu > li .mega-menu-submenu').hide();
        $('.mega-menu > li').removeClass('active');
    }

    var menuChildrenWidth = 0;
    megaMenu.children('li').each(function () {
        menuChildrenWidth += $(this).outerWidth();
    });

    var menuPadding = parseInt(((megaMenu.outerWidth() - menuChildrenWidth) / megaMenu.children('li').length) / 2);

    $(".mega-menu > li").css('padding', '0 ' + menuPadding + 'px').show().hover(function () {
        //reset all items before process 
        $('.mega-menu-submenu').hide();
        $(".mega-menu > li").removeClass('active');

        //reset all items before process 
        var submenu = $(this).children('.mega-menu-submenu');
        $(this).addClass('active');
        submenu.css('left', '-9999px').show();
        submenu.css('top', $(this).height()) + 'px';
        submenu.width(submenu.find('.column').length * submenu.find('.column:first').outerWidth());

        if ($(this).offset().left < ($(window).width() / 2)) {
            //left side
            var submenuLeft = ($(this).offset().left)
            if ((megaMenu.position().left + megaMenu.outerWidth()) < submenuLeft + submenu.outerWidth()) {
                submenuLeft -= (submenuLeft + submenu.outerWidth()) - (megaMenu.position().left + megaMenu.outerWidth());
            }
            submenu.css('left', submenuLeft - Math.round($('.mega-menu').offset().left) + 'px');
        } else {
            submenu.css('left', 0);
            var submenuLeft = ($(this).offset().left) - ((submenu.outerWidth(false)) - $(this).outerWidth(false));

            if (megaMenu.position().left > submenuLeft) {
                submenuLeft = megaMenu.position().left;
            }

            submenu.css('left', submenuLeft - Math.round($('.mega-menu').offset().left) + 'px');
        }
    },
    function () {
        $(this).children('.mega-menu-submenu').hide();
        $(this).removeClass('active');
    });
}